import type {
  SearchBaseSelectors,
  SearchPageSelectors,
} from '../../../../../../module/page_enhancer/appearance/style_enhancement/platforms'
import { ThemeVarService } from '../../../../../../lib/abstract/style/theme_var/service'
import { PageHandler } from '../../../../../../lib/page_handler'
import { ToolKit } from '../../../../../../lib/utils/toolkit'
import { AppStyleCollections, logger } from '../../../../../../types/constants'

export class SearchCommonStyles {
  private readonly name: string = 'SearchCommonStyles'
  private static instance: SearchCommonStyles
  private readonly themeVarService: ThemeVarService = ThemeVarService.getInstance()
  private readonly pageType = PageHandler.getCurrentPageType()
  private observer: MutationObserver | null = null

  /**
   * 获取单例实例
   */
  static getInstance(): SearchCommonStyles {
    if (!SearchCommonStyles.instance) {
      SearchCommonStyles.instance = new SearchCommonStyles()
    }
    return SearchCommonStyles.instance
  }

  startMonitoring(config: SearchPageSelectors, options: {
    monitorSelector: string // 监控选择器
    monitorConfig?: MutationObserverInit // MutationObserver配置
    triggerCondition?: (mutations: MutationRecord[]) => boolean // 触发条件函数
    shouldShowSuggestions?: () => boolean // 是否显示搜索建议的额外条件函数
    shouldShowHistory?: () => boolean // 是否显示搜索历史的额外条件函数
  }): void {
    const {
      monitorSelector,
      monitorConfig = {
        childList: true, // 直接子节点
        subtree: false, // 所有后代节点
      },
      triggerCondition = (mutations: MutationRecord[]) => mutations.some(mutation => mutation.type === 'childList'), // 默认触发条件：子节点变化
      shouldShowSuggestions = () => true,
      shouldShowHistory = () => true,
    } = options

    const currentConfig = config[this.pageType]

    if (!currentConfig) {
      logger.warn(`[${this.name}] 未找到选择器配置`)
      return
    }

    // 1. 先检查是否已存在观察器，避免重复创建
    this.stopMonitoring()

    // 2. 使用节流优化频繁的 DOM 操作
    const checkAndToggle = ToolKit.func.throttle(() => {
      this.toggleSearchClass(currentConfig, shouldShowSuggestions, shouldShowHistory)
    }, 300)

    // 3. 创建 MutationObserver
    this.observer = new MutationObserver((mutations) => {
      const hasRelevantChange = triggerCondition(mutations)

      if (hasRelevantChange) {
        checkAndToggle()
      }
    })

    // 4. 查找目标元素（支持多个目标）
    const targets = document.querySelectorAll(monitorSelector)

    if (targets.length === 0) {
      logger.warn(`[${this.name}] 未找到元素，跳过观察`, monitorSelector)
      return
    }

    // 5. 观察所有相关目标
    targets.forEach((target) => {
      this.observer!.observe(target, monitorConfig)
    })

    // 6. 立即执行一次初始检查
    checkAndToggle()

    logger.attention(`[${this.name}] 正在监控搜索`, monitorSelector)
  }

  /**
   * 停止监控
   */
  stopMonitoring(): void {
    this.observer?.disconnect()
    this.observer = null
  }

  /**
   * 切换搜索类名
   */
  private toggleSearchClass(
    config: SearchBaseSelectors,
    shouldShowSuggestions: () => boolean,
    shouldShowHistory: () => boolean,
  ): void {
    const hasSuggestions = $(config.searchBox.dropdown.suggestions).length > 0
    const $element = $(config.searchBox.dropdown.wrapper)

    const showSuggestions = hasSuggestions && shouldShowSuggestions()
    const showHistory = !hasSuggestions && shouldShowHistory()

    $element
      .toggleClass(AppStyleCollections.Search.class.SEARCH_SUGGESTIONS, showSuggestions)
      .toggleClass(AppStyleCollections.Search.class.SEARCH_HISTORY, showHistory)

    if (!showSuggestions && !showHistory) {
      $element
        .removeClass(AppStyleCollections.Search.class.SEARCH_SUGGESTIONS)
        .removeClass(AppStyleCollections.Search.class.SEARCH_HISTORY)
    }
  }

  /**
   * 绑定输入事件
   */
  bindInputEvent(config: SearchBaseSelectors, checkHistoryEmpty?: (config: SearchBaseSelectors) => boolean): void {
    const $input = $(config.searchBox.input)

    if (!$input || $input.length === 0) {
      logger.warn(`[${this.name}] 未找到搜索输入框`, config.searchBox.input)
      return
    }

    const throttledUpdate = ToolKit.func.throttle(() => {
      this.updateFormAttrs($input, config, checkHistoryEmpty)
    }, 250)

    $input
      .off('input focus click') // 先解绑避免重复绑定
      .on('input focus click', throttledUpdate)
    this.updateFormAttrs($input, config, checkHistoryEmpty)
  }

  /**
   * 更新表单属性
   */
  updateFormAttrs($input: JQuery<HTMLElement>, config: SearchBaseSelectors, checkHistoryEmpty?: (config: SearchBaseSelectors) => boolean): void {
    const $form = $(config.searchBox.form || '')
    const dropdown = config.searchBox.dropdown

    if ($input.val() === '' || $input.val() === null) {
      // 当搜索关键词为空时强制设置特定值
      $form
        .attr(AppStyleCollections.Search.attr.IS_HISTORY_EMPTY, 'false')
        .attr(AppStyleCollections.Search.attr.IS_SUGGESTIONS_EMPTY, 'true')

      // 用于检查是否有热门搜索等
      if (checkHistoryEmpty && checkHistoryEmpty(config)) {
        $form.attr(AppStyleCollections.Search.attr.IS_HISTORY_EMPTY, 'true')
      }
    }
    else {
      $form
        .attr(
          AppStyleCollections.Search.attr.IS_HISTORY_EMPTY,
          $(dropdown.history).length > 0 ? 'false' : 'true',
        )
        .attr(
          AppStyleCollections.Search.attr.IS_SUGGESTIONS_EMPTY,
          $(dropdown.suggestions).length > 0 ? 'false' : 'true',
        )
    }
  }

  titleStyles(selector: string = 'a', highlightTag: string = 'em'): string {
    return `
/* 去掉标题的下划线 */
${selector} {
  text-decoration: none !important;
  color: var(${this.themeVarService.link.default.text}) !important;
  
  &:hover {
    text-decoration: none !important;
    color: var(${this.themeVarService.link.default.textHover}) !important;
    
    ${highlightTag} {
      text-decoration: none !important;
    }
  }
  
  ${highlightTag} {
    text-decoration: none !important;
  }
}
    `
  }

  /**
   * 搜索分类样式
   */
  searchTabStyles(options: {
    container?: string
    selector?: string
    tag?: string
    activeClass: string
  }): string {
    const { container = 'ul', selector = 'li', tag = 'a', activeClass = 'active' } = options

    return `
  ${container} {
    > ${selector} {

      /* 悬浮 */
      &:hover {
        ${tag} {
          color: var(${this.themeVarService.tab.textHover}) !important;
        }
        
        &:not(.${activeClass}) {
          border-bottom: none !important;
        }
      }
      
      /* 当前页 */
      &.${activeClass} {
        border-bottom: ${this.themeVarService.tab.borderBottom} !important;
        border-color: var(${this.themeVarService.tab.borderActive}) !important;
        font-weight: 700 !important;

        &::after {
          background: var(${this.themeVarService.tab.textActive}) !important;
        }

        ${tag} {
          color: var(${this.themeVarService.tab.textActive}) !important;
        }
      }
      
      /* 其他页 */
      ${tag} {
        color: var(${this.themeVarService.tab.text}) !important;
        font-size: ${this.themeVarService.tab.fontSize} !important;
        font-weight: 400 !important;
      }
    }
  }
    `
  }

  /**
   * 搜索结果列表容器样式
   */
  resultContainerStyles(
    options?: {
      setGap?: boolean
      fullWidth?: boolean
      columns?: number
    },
  ): string {
    const { setGap = true, fullWidth = true, columns = 1 } = options || {}

    return `
      display: grid !important;
      grid-template-columns: repeat(${columns}, auto);
      justify-content: center !important;
      ${setGap ? `gap: ${this.themeVarService.search.resultItem.gap} !important;` : ''}
      ${fullWidth ? 'width: 100% !important;' : ''}
    `
  }

  /**
   * 搜索结果项样式
   */
  resultItemStyles(
    options?: {
      relativePosition?: boolean
      setPadding?: boolean
      overflowHide?: boolean
      showBorder?: boolean
      noMarginBottom?: boolean
      fullWidth?: boolean
      extraStyles?: string
    },
  ): string {
    const { relativePosition = true, setPadding = true, overflowHide = true, showBorder = false, noMarginBottom = false, fullWidth = false, extraStyles = '' } = options || {}

    return `
      ${relativePosition ? 'position: relative !important;' : ''}
      background: var(${this.themeVarService.search.resultItem.background}) !important;
      box-shadow: var(${this.themeVarService.search.resultItem.shadow}) !important;
      border-radius: ${this.themeVarService.search.resultItem.borderRadius} !important;
      ${setPadding ? `padding: ${this.themeVarService.search.resultItem.padding} !important;` : ''}
      ${overflowHide ? 'overflow: hidden !important;' : ''}
      ${showBorder ? '' : 'border: none !important;'}
      ${noMarginBottom ? 'margin-bottom: 0 !important;' : ''}
      ${fullWidth ? 'width: 100% !important;' : ''}
      ${extraStyles}
    `
  }

  /**
   * 搜索结果其他项样式
   */
  resultOtherStyles(): string {
    return `
      grid-column: 1 / -1 !important;
      grid-row: auto !important;
      justify-self: center !important;
    `
  }
}
